package cn.com.lms.business.course.web;

import cn.com.lms.business.core.constant.CourseTypeEnum;
import cn.com.lms.business.core.constant.BNZConstants;
import cn.com.lms.business.core.util.FastDfsUtils;
import cn.com.lms.business.course.persistence.entity.FbCourseInfo;
import cn.com.lms.business.course.persistence.entity.vo.CourseInfoVo;
import cn.com.lms.business.course.service.FbCourseInfoService;
import com.bnzj.core.exception.BusinessException;
import com.bnzj.core.rest.ResponseResult;
import com.bnzj.core.rest.ResultCode;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/*
 * @author liuwei
 * @date 2020/3/16 13:40
 * @desc //课程模块controller
 */
@Tag(name = "课程信息", description = "课程信息API")
@RestController
@RequestMapping("/course")
public class CourserInfoController {
    protected static final Logger logger = LoggerFactory.getLogger(CourserInfoController.class);

    @Autowired
    private FbCourseInfoService courseInfoService;


    @Autowired
    private FastDfsUtils fastDfsUtils;


    @Operation(summary = "课程列表分页查询", description = "课程列表分页查询", parameters = {
            @Parameter(name = "title", description = "课程标题", allowReserved = true, schema = @Schema(type = "String", description = "课程标题")),
            @Parameter(name = "courseType", description = "课程类型", allowReserved = true, schema = @Schema(type = "String", description = "课程类型")),
            @Parameter(name = "categoryId", description = "课程目录id", allowReserved = true, schema = @Schema(type = "String", description = "课程目录id")),
            @Parameter(name = "recommendSort", description = "推荐值排序(desc 降序  asc升序)", allowReserved = true, schema = @Schema(type = "String", description = "推荐值排序")),
            @Parameter(name = "scoreSort", description = "评分排序(desc 降序  asc升序)", allowReserved = true, schema = @Schema(type = "String", description = "评分排序")),
            @Parameter(name = "timeSort", description = "更新时间排序(desc 降序  asc升序)", allowReserved = true, schema = @Schema(type = "String", description = "更新时间排序")),
            @Parameter(name = "liveStartTime", description = "直播时间(desc 降序  asc升序)", allowReserved = true, schema = @Schema(type = "String", description = "直播时间排序")),
            @Parameter(name = "limit", description = "分页大小", allowReserved = true, schema = @Schema(type = "int", description = "分页大小")),
            @Parameter(name = "offset", description = "页码", allowReserved = true, schema = @Schema(type = "int", description = "页码")),
    })
    @GetMapping("/getList")
    public ResponseResult<Page<FbCourseInfo>> queryCourseListPage(HttpServletRequest request) {
        String title = request.getParameter("title");
        String categoryId = request.getParameter("categoryId");
        String recommendSort = request.getParameter("recommendSort");
        String scoreSort = request.getParameter("scoreSort");
        String timeSort = request.getParameter("timeSort");
        String courseTypeId = request.getParameter("courseType");
        String liveStartTime = request.getParameter("liveStartTime");
        return courseInfoService.queryCourseListPage(request, title, categoryId, recommendSort, scoreSort, timeSort, liveStartTime, courseTypeId);
    }

    /*
     * @author liuwei
     * @date 2020/3/16 18:39
     * @desc 获取课程类型
     */
    @Operation(summary = "获取课程类型")
    @GetMapping("/getDictionaryList")
    public ResponseResult<List<Map<String, Object>>> getDictionaryList() {
        return ResponseResult.success(courseInfoService.getCourseTypeDictionary(BNZConstants.COURSE_TYPE_CODE));
    }


    /*
     * @author liuwei
     * @date 2020/3/17 16:58
     * @desc 新增或者修改课程
     */
    @Operation(summary = "新增或者修改课程")
    @PostMapping("/saveOrUpdateCourse")
    public ResponseResult saveOrUpdateCourse(@RequestBody CourseInfoVo infoVo) throws Exception {
        /*String courseType = getCourseType(infoVo.getCourseFile());
        if (null == courseType) {
            return ResponseResult.failure(0, "url地址错误!");
        }*/
        try {
            return courseInfoService.saveCourse(infoVo, infoVo.getCourseType());
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResponseResult.bizException(new BusinessException(e.getMessage(), 0));
        }
    }


    /*
     * @author liuwei
     * @date 2020/3/17 15:14
     * @desc 上传课程文件
     */
//    @Operation(summary = "上传课程文件")
//    @PostMapping("/upload")
//    public ResponseResult uploadFile(@Parameter(name = "file", required = true) @RequestParam(value = "file") MultipartFile file) {
//        String suffix = getCourseType(file.getOriginalFilename());
//        if (null == suffix || CourseTypeEnum.LIVE.getCode().equals(suffix)) {
//            return ResponseResult.failure(0, "上传文件格式错误!");
//        } else {
//            return fastDfsUtils.uploadFile(file);
//        }
//    }

    /*
     * @author liuwei
     * @date 2020/3/17 15:14
     * @desc 上传课程文件
     */
    @Operation(summary = "上传课程文件")
    @PostMapping("/uploadBase64")
    public ResponseResult uploadFileBase64(@Parameter(name = "file", required = true) @RequestParam(value = "file") MultipartFile file) {
//        String suffix = getCourseType(file.getOriginalFilename());
//        if (null == suffix || CourseTypeEnum.LIVE.getCode().equals(suffix)) {
//            return ResponseResult.failure(0, "上传文件格式错误!");
//        } else {
//
//        }
        return fastDfsUtils.uploadFileBase64(file);
    }

    /*
     * @author lixin
     * @date 2020/5/9 16:58
     * @desc 阿里云上传课程文件
     */
    @Operation(summary = "上传课程文件")
    @PostMapping("/upload")
    public ResponseResult uploadFile(@Parameter(name = "file", required = true) @RequestParam(value = "file") MultipartFile file) {

        String suffix = getCourseType(file.getOriginalFilename());
        if (null == suffix || CourseTypeEnum.LIVE.getCode().equals(suffix)) {
            return ResponseResult.failure(0, "上传文件格式错误!");
        }
        else if(null == suffix || CourseTypeEnum.VIDEO.getCode().equals(suffix)){
            return fastDfsUtils.uploadALiYunFile(file);
        }
        else if(null == suffix || CourseTypeEnum.OTHER.getCode().equals(suffix)){
            return fastDfsUtils.uploadFileAvatar(file);

        }
        return ResponseResult.failure(0,"");

    }

    @Operation(summary = "阿里云上传课程文件")
    @PostMapping("/uploadALiYun")
    public ResponseResult uploadALiYunFile(@Parameter(name = "file", required = true) @RequestParam(value = "file") MultipartFile file) {
        String suffix = getCourseType(file.getOriginalFilename());
        if (null == suffix || CourseTypeEnum.LIVE.getCode().equals(suffix)) {
            return ResponseResult.failure(0, "上传文件格式错误!");
        } else {
            return fastDfsUtils.uploadALiYunFile(file);
        }
    }


    /*
     * @author liuwei
     * @date 2020/3/17 16:58
     * @desc 删除课程
     */
    @Operation(summary = "删除课程")
    @GetMapping("/delCourse/{courseId}")
    public ResponseResult delCourse(@Parameter(description = "课程主键", name = "courseId", required = true) @PathVariable(value = "courseId") Long courseId) {
        try {
            return courseInfoService.delCourse(courseId);
        } catch (Exception e) {
//            e.printStackTrace();
            return ResponseResult.bizException(new BusinessException(e.getMessage(),
                    String.valueOf(ResultCode.FAILURE)));
        }
    }

    @Operation(summary = "改变课程看完值")
    @GetMapping("/changeCourseOver/{courseId}")
    public ResponseResult overCourse(@Parameter(description = "课程主键", name = "courseId", required = true) @PathVariable(value = "courseId") Long courseId) {
        try {
            return courseInfoService.overCourse(courseId);
        } catch (Exception e) {
//            e.printStackTrace();
            return ResponseResult.bizException(new BusinessException(e.getMessage(),
                    String.valueOf(ResultCode.FAILURE)));
        }
    }



    @Operation(summary = "获取课程Url")
    @GetMapping("/getUrlByCourseId/{courseId}")
    public ResponseResult<String> getUrlByCourseId(@Parameter(description = "课程主键", name = "courseId", required = true) @PathVariable(value = "courseId") Long courseId) {
        return ResponseResult.success(courseInfoService.getgetUrlById(courseId));
    }

    @Operation(summary = "获取课程是否看完")
    @GetMapping("/getCourseIsOver/{courseId}")
    public ResponseResult<String> getCourseIsOver(@Parameter(description = "课程主键", name = "courseId", required = true) @PathVariable(value = "courseId") Long courseId) {
        return ResponseResult.success(courseInfoService.getIsOverById(courseId));
    }

    public String getCourseType(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return CourseTypeEnum.LIVE.getCode();
        }
        if (fileUrl.lastIndexOf(".") < 0) {
            return null;
        }
        String suffix = fileUrl.substring(fileUrl.lastIndexOf("."));
        if (suffix.equals(BNZConstants.AVI) || suffix.equals(BNZConstants.MP4)) {
            return CourseTypeEnum.VIDEO.getCode();
        } else if (suffix.equals(BNZConstants.DOC) || suffix.equals(BNZConstants.JPG) || suffix.equals(BNZConstants.PNG) || suffix.equals(BNZConstants.PPT) || suffix.equals(BNZConstants.PDF)
                || suffix.equals(BNZConstants.DOCX) || suffix.equals(BNZConstants.PPTX) || suffix.equals(BNZConstants.XLSX) || suffix.equals(BNZConstants.XLS)) {
            return CourseTypeEnum.OTHER.getCode();
        } else {
            return null;
        }
    }

//    @GetMapping("/findvod/{courseId}")
//    public ResponseResult findVodById(@PathVariable Long courseId) {
//        Optional<FbCourseInfo> byId = courseInfoService.findById(courseId);
//    }

    @Operation(summary = "机构的课程列表", description = "机构的课程列表", parameters = {
            @Parameter(name = "groupId", description = "机构id", allowReserved = true, schema = @Schema(type = "String", description = "机构id"))
    })
    @GetMapping("/getGroupCourseList")
    public ResponseResult<List<FbCourseInfo>> getGroupCourseList(HttpServletRequest request) {
        String groupId = request.getParameter("groupId");
        List<FbCourseInfo> list = courseInfoService.getCourseListByGroupId(groupId);
        return ResponseResult.success(list);
    }



}
